package com.common.app.data.repository

import com.common.app.data.api.ApiConstant.getBaseUrl
import com.common.app.data.bean.AppConfigBean
import com.common.app.data.bean.AdInfoBean
import com.common.app.data.bean.SSEEvent
import com.common.app.data.bean.VersionResBean
import com.common.app.utls.network.RxHttpManager
import com.common.app.utls.network.interceptor.HeadUrlInterceptor
import com.common.base.app.extras.no
import com.common.base.data.CommonBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flattenConcat
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import rxhttp.toAwait
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp
import java.util.concurrent.TimeUnit

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/6/19
 * <p>
 * 描述：SSE通用
 * <p>
 * 修订历史：
 */
object SseApi {

    // SSE 连接端点
    private val SSE_ENDPOINT = getBaseUrl() + "api/v1/smart-ring/vital-sign/download"
//    private val SSE_ENDPOINT = getBaseUrl() + "api/v1/smart-ring/vital-sign/download-direct"//测试接口

    /**
     * 创建专用于SSE的OkHttpClient，不包含ResponseInterceptor
     */
    private fun createSseOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(0, TimeUnit.SECONDS) // SSE需要长连接
            .writeTimeout(15, TimeUnit.SECONDS)
            .addInterceptor(HeadUrlInterceptor())
            // 不添加ResponseInterceptor，让错误直接传递
            .build()
    }

    // 获取SSE连接的Response对象
    suspend fun getSseResponse() =
        withContext(Dispatchers.IO) {
            RxHttp.get(SSE_ENDPOINT)
                .addHeader("Accept", "text/event-stream")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
                .toAwait<SSEEvent>()
                .await()
        }

    suspend fun getSseResponse2(): Response =
        withContext(Dispatchers.IO) {
            RxHttp.get(SSE_ENDPOINT)
                .addHeader("Accept", "text/event-stream")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Connection", "keep-alive")
                .execute()
        }

    /**
     * 使用toFlow方法获取SSE流
     */
    fun getSseFlow(staTime: String? = "", endTime: String? = ""): Flow<String> = flow {
        val response = RxHttp.get(SSE_ENDPOINT)
            .addHeader("Accept", "text/event-stream")
            .addHeader("Cache-Control", "no-cache")
            .addPath("endTime", endTime)
//            .execute() // 这里会执行网络请求
        staTime.isNullOrEmpty().no {
            response.addPath("startTime", staTime)
        }
        endTime.isNullOrEmpty().no {
            response.addPath("endTime", endTime)
        }

        response.execute().body?.source()?.use { source ->
            while (!source.exhausted()) {
                source.readUtf8Line()?.let { line ->
                    if (line.startsWith("data: ")) {
                        emit(line.substring(6))
                    }
                }
            }
        }
    }.flowOn(Dispatchers.IO) // 确保整个Flow在IO线程执行


    /**
     * 使用toFlow方法获取SSE流
     */
    fun getSseFlow2(dataType: String? = "", staTime: String? = "", endTime: String? = ""): Flow<String> = flow {
        val response = RxHttp.postJson(SSE_ENDPOINT)
            .addHeader("Accept", "text/event-stream")
            .addHeader("Cache-Control", "no-cache")
            .setOkClient(createSseOkHttpClient()) // 使用专用客户端

        dataType.isNullOrEmpty().no {
            response.add("data_type", dataType)
        }
        staTime.isNullOrEmpty().no {
            response.add("start_timestamp", staTime)
        }
        endTime.isNullOrEmpty().no {
            response.add("end_timestamp", endTime)
        }
        val responseEx = response.execute()

        // 手动检查状态码
        if (responseEx.code != 200) {
            throw Exception("Server error: ${responseEx.code} ${responseEx.message}")
        }

        responseEx.body?.source()?.use { source ->
            while (!source.exhausted()) {
                source.readUtf8Line()?.let { line ->
                    if (line.startsWith("data: ")) {
                        emit(line.substring(6))
                    }
                }
            }
        }
    }.flowOn(Dispatchers.IO)
}